package com.yikaiye.android.yikaiye.ui.activity.mine;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropImageEngine;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.application.MyApplication;
import com.yikaiye.android.yikaiye.base.BaseActivity;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.ActivityUserInfoBinding;
import com.yikaiye.android.yikaiye.model.EventBusModel;
import com.yikaiye.android.yikaiye.model.UserModel;
import com.yikaiye.android.yikaiye.ui.activity.mine.viewmodel.UserInfoViewModel;
import com.yikaiye.android.yikaiye.ui.adapter.PhoneNumberAdapter;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.ToastHelper;
import com.yikaiye.android.yikaiye.utils.UMengUtil;
import com.yikaiye.android.yikaiye.utils.pictrue.GlideEngine;
import com.yikaiye.android.yikaiye.utils.pictrue.ImageLoaderUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

/**
 * 个人信息
 */
public class UserInfoActivity extends BaseActivity<ActivityUserInfoBinding, UserInfoViewModel> {

    private ActivityResultLauncher<Intent> launcherResult;
    public static final int SET_REAL_NAME = 1003;
    private PhoneNumberAdapter phoneNumberAdapter;

    @Override
    protected UserInfoViewModel bindModel() {
        return getViewModel(this, UserInfoViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.user_info));
        launcherResult = createActivityResultLauncher();
        viewModel.getUserInfo();
        phoneNumberAdapter = new PhoneNumberAdapter(context);
        binding.recyclerView.setAdapter(phoneNumberAdapter);
    }

    @Override
    protected void initClick() {
        // 用户信息
        viewModel.userModelMutableLiveData.observe(this, userModel -> {
            if (null != userModel) {
                binding.tvNickname.setText(TextUtils.isEmpty(userModel.getUsername()) ? getString(R.string.common_user) : userModel.getUsername());
                Glide.with(MyApplication.getContext()).load(userModel.getAvatar()).placeholder(R.mipmap.icon_head_def).error(R.mipmap.icon_head_def).into(binding.ivHead);
                UserModel.CustomerModel customerModel = userModel.getCustomer();
                if (customerModel != null) {
                    binding.fullNameTv.setText(customerModel.getCustomerName());
                    // 性别字段取值客户gender：1男，2女，3未知
                    binding.tvSex.setText(customerModel.getGender() == 1 ? getString(R.string.gender_boy) : customerModel.getGender() == 2 ? getString(R.string.gender_girl) : getString(R.string.gender_x));
                    // auditStatus 审核状态：1：待审核，2：审核通过，3：审核失败
                    binding.authStatusIv.setImageResource(customerModel.getAuditStatus() == 2 ? R.mipmap.icon_auth_yes : R.mipmap.icon_mine_no_auth);
                }
                if (userModel.getMergeTels() != null) {
                    phoneNumberAdapter.submitList(userModel.getMergeTels());
                }
            }
        });

        viewModel.onDelayClick(binding.llHead, o -> chooseImage());

        viewModel.onDelayClick(binding.llNickname, o -> {
            UMengUtil.setCountEventId(Constant.REAL_NAME_VERIFIED_CLICK);
            Bundle bundle = new Bundle();
            bundle.putString(Constant.USER_NAME_KEY, binding.tvNickname.getText().toString().trim());
            JumpIntent.jump(UserInfoActivity.this, NicknameActivity.class, bundle, SET_REAL_NAME);
        });

        // 修改头像成功
        viewModel.urlMutableLiveData.observe(this, s -> {
            Glide.with(context).load(s).placeholder(R.mipmap.icon_head_def).error(R.mipmap.icon_head_def).into(binding.ivHead);
            Map<String, Object> map = new HashMap<>();
            map.put("avatar", s);
            map.put("userDetailId", MyApplication.manager.getUserDetailId());
            viewModel.updateUserInfo(map);
        });
        // 修改头像失败
        viewModel.uploadErrorMutableLiveData.observe(this, s -> dismissLoadingDialog());

        // 修改个人信息
        viewModel.changeSuccessMutableLiveData.observe(this, s -> {
            ToastHelper.show(getString(R.string.change_successfully));
            EventBus.getDefault().post(new EventBusModel(Constant.refreshUserInfo));
            dismissLoadingDialog();
        });
        viewModel.changeErrorMutableLiveData.observe(this, s -> {
            ToastHelper.show(s);
            dismissLoadingDialog();
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == UserInfoActivity.RESULT_OK) {
            if (requestCode == SET_REAL_NAME) {
                if (data != null) {
                    String userName = data.getStringExtra(Constant.USER_NAME_KEY);
                    binding.tvNickname.setText(userName);
                }
            }
        }
    }

    private void chooseImage() {
        PictureSelector.create(context).openGallery(SelectMimeType.ofImage()) // 全部.SelectMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .setImageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                .setSelectorUIStyle(new PictureSelectorStyle()).setCameraImageFormat(PictureMimeType.PNG) // 拍照保存图片格式后缀,默认jpeg,Android Q使用PictureMimeType.PNG_Q
                .setSelectionMode(SelectModeConfig.SINGLE) // 单选
                .setCropEngine((fragment, srcUri, destinationUri, dataSource, requestCode) -> { // 裁剪
                    UCrop.Options options = new UCrop.Options();
                    options.withAspectRatio(1, 1);
                    UCrop uCrop = UCrop.of(srcUri, destinationUri, dataSource);
                    uCrop.withOptions(options);
                    uCrop.setImageEngine(new UCropImageEngine() {
                        @Override
                        public void loadImage(Context context, String url, ImageView imageView) {
                            if (!ImageLoaderUtils.assertValidRequest(context)) {
                                return;
                            }
                            Glide.with(context).load(url).override(180, 180).into(imageView);
                        }

                        @Override
                        public void loadImage(Context context, Uri url, int maxWidth, int maxHeight, OnCallbackListener<Bitmap> call) {
                            Glide.with(context).asBitmap().load(url).override(maxWidth, maxHeight).into(new CustomTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    if (call != null) {
                                        call.onCall(resource);
                                    }
                                }

                                @Override
                                public void onLoadCleared(@Nullable Drawable placeholder) {
                                    if (call != null) {
                                        call.onCall(null);
                                    }
                                }
                            });
                        }
                    });
                    uCrop.start(fragment.requireActivity(), fragment, requestCode);
                }).setCompressEngine((CompressFileEngine) (context, source, call) -> Luban.with(context).load(source).ignoreBy(100) // 小于多少kb的图片不压缩
                        .setCompressListener(new OnNewCompressListener() {
                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onSuccess(String source, File compressFile) {
                                if (call != null) {
                                    call.onCallback(source, compressFile.getAbsolutePath());
                                }
                            }

                            @Override
                            public void onError(String source, Throwable e) {
                                if (call != null) {
                                    call.onCallback(source, null);
                                }
                            }
                        }).launch()).forResult(launcherResult);
    }

    /**
     * 创建一个ActivityResultLauncher
     */
    private ActivityResultLauncher<Intent> createActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            int resultCode = result.getResultCode();
            if (resultCode == RESULT_OK) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(result.getData());
                for (int i = 0; i < selectList.size(); i++) {
                    LocalMedia media = selectList.get(i);
                    File file = new File(media.getCompressPath() == null ? media.getRealPath() : media.getCompressPath());
                    viewModel.uploadHeadImg(file);
                }
            }
        });
    }
}